#include "MorphologyErosion.h"

MorphologyErosion::MorphologyErosion (const Core< int > & structElem)
: Morphology (structElem)
{

}



MorphologyErosion::~MorphologyErosion ()
{

}



Ptr< QImage > MorphologyErosion::operate (Ptr< QImage > pSrcImage)
{
  QSize structSize = __structElem.getSize ();
  QPoint structCenter = __structElem.getCenter ();

  Ptr< QImage > pDestImage = new QImage (
    pSrcImage->size (), QImage::Format_ARGB32);

  int lineBytes = pSrcImage->bytesPerLine ();
  uchar * srcData = pSrcImage->bits ();

  for (int v = 0; v < pSrcImage->height (); ++v) {
    QRgb * destLine = (QRgb*)pDestImage->scanLine (v);
    QRgb * srcLine = (QRgb*)pSrcImage->scanLine (v);
    for (int u = 0; u < pSrcImage->width (); ++u) {
      uchar a = qAlpha (srcLine[u]);
      uchar minVal = 255;
      for (int x = 0; x < structSize.width (); ++x) {
        for (int y = 0; y < structSize.height (); ++y) {
          int u1 = u + (x - structCenter.x ());
          int v1 = v + (y - structCenter.y ());
          if (u1 < 0 || u1 >= pSrcImage->width () || v1 < 0
                  || v1 >= pSrcImage->height ())
            continue;
          int val = qGray (((QRgb *)(srcData + lineBytes * v1))[u1])
            - __structElem (x, y);
          if (val < minVal)
            minVal = (val < 0 ? 0 : val);
        }
      }
      destLine[u] = qRgba (minVal, minVal, minVal, a);
    }
  }
  return pDestImage;
}
